﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using YSL.Application.Services.Qiniu;

namespace YSL.Api.Host.Controllers
{
    /// <summary>
    /// 七牛云服务
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class QIniuController : ControllerBase
    {
        private readonly QiniuService _qiniuService;

        public QIniuController(QiniuService qiniuService)
        {
            _qiniuService = qiniuService;
        }
        /// <summary>
        /// 七牛云上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("UploadImage")]
        public async Task<IActionResult> UploadImage(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return BadRequest("文件为空");

            try
            {
                // 生成唯一文件名（避免重复）
                string fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
                using (var stream = file.OpenReadStream())
                {
                    string url = _qiniuService.Upload(stream, fileName);
                    return Ok(new { Url = url });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }
    }
}
